<template>
  <div>
    <van-search
      v-model="keyword"
      show-action
      label="地址"
      background="#0cf0e4"
      placeholder="请输入搜索关键词"
      size="16"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <div class="hiswrap">
      <h4>搜索记录</h4>
      <div class="history">
        <div class="his" v-if="!history.length">暂无搜索记录</div>
        <div class="his" @click="clickHis(his)" v-for="his in history" :key="his">
          {{ his }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      keyword: '', // 关键字
      // 使用缓存一定要做判断，写个三目，判断是否是第一次进入搜索页，是才开始存，不是就得清空数组
      history: localStorage.getItem('his')
        ? JSON.parse(localStorage.getItem('his'))
        : []
    }
  },
  methods: {
    // word 就是点击的那个记录
    clickHis (word) {
      // 点击历史记录能够回到之前的记录页面
      // 把his赋值给keyword
      this.keyword = word
      this.onSearch()
    },
    onSearch () {
      // 存储 搜索记录
      /* 先取  取完转成数组  操作数据  JSON.stringify存回去
      */
      let his = localStorage.getItem('his')
        ? JSON.parse(localStorage.getItem('his'))
        : []
      // 在数组头部添加一个关键字
      his.unshift(this.keyword)
      his = [...new Set(his)]
      if (his.length >= 3) {
        his.length = 3
      }
      /* 后存回去 */
      localStorage.setItem('his', JSON.stringify(his))
      // 进入列表结果页
      this.$router.push({
        path: '/searchResult',
        query: {
          keyword: this.keyword
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.history{
  display: flex;
  font-size: 12px;
  flex-wrap: wrap;
  .his{
    background-color: rgb(245, 242, 242);
    margin: 5px;
    padding: 6px;
    border-radius: 10px;
  }
}
</style>
